//
//  DZYHUD.swift
//  globalcarbusiness
//
//  Created by dongzhenyu on 2017/8/17.
//  Copyright © 2017年 dongzhenyu. All rights reserved.
//


public enum DZYHUDShowType {
    case success
    case failure
    case alert
}

public typealias DZYHUDComplectionBlock = () -> Void

import UIKit
import MBProgressHUD
import Foundation
import Gifu

public class DZYHUD: UIView {
    
    var hud: MBProgressHUD?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUserInterface()
    }
    
    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUserInterface()
    }
    
    func setupUserInterface() {
        backgroundColor = UIColor.clear
        
        let animateImageView = GIFImageView()
        animateImageView.animate(withGIFNamed: "CodeBookLoading", loopCount: 0)
        
        hud = MBProgressHUD.showAdded(to: self, animated: false)
        hud?.isSquare = true
        hud?.mode = .customView
        hud?.customView = animateImageView
        hud?.removeFromSuperViewOnHide = true
        hud?.label.textColor = UIColor.cdTintColor()
        hud?.label.font = UIFont.systemFont(ofSize: 16.0)
        hud?.bezelView.backgroundColor = backgroundColor
    }
}

public extension UIViewController {
    private struct HUDAssociatedKeys {
        static var DZYHUD = "CodeBookDKHUD"
    }
    
    // MARK: - HUD 相关
    
    var HUD: DZYHUD? {
        get {
            var hud = objc_getAssociatedObject(self, &HUDAssociatedKeys.DZYHUD) as? DZYHUD
            if hud == nil {
                hud = DZYHUD()
                objc_setAssociatedObject(self, &HUDAssociatedKeys.DZYHUD, hud!, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            }
            return hud
        }
        set {
            objc_setAssociatedObject(self, &HUDAssociatedKeys.DZYHUD, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    /* 显示 HUD */
    func showHUD() {
        view.addSubview(HUD!)
        view.bringSubview(toFront: HUD!)
        HUD?.snp.updateConstraints { make -> Void in
            make.edges.equalToSuperview()
        }
    }
    
    /* 隐藏 HUD */
    func hideHUD() {
        DispatchQueue.main.async { [weak self] in
            if self?.HUD != nil {
                MBProgressHUD.hide(for: (self?.HUD)!, animated: false)
                self?.HUD?.removeFromSuperview()
                self?.HUD = nil
            }
        }
    }
    
    func showLoading(_ text: String? = nil, isWhiteBackground: Bool? = nil, isCovered: Bool? = nil) {
        let showView = isCovered != nil && isCovered! ? (UIApplication.shared.delegate?.window)! : view
        let hud = MBProgressHUD.showAdded(to: showView!, animated: true)
        hud.animationType = .fade
        hud.removeFromSuperViewOnHide = true
        hud.label.text = text != nil ? text! : ""
        if isWhiteBackground != nil && isWhiteBackground! {
            hud.contentColor = UIColor.black
            hud.bezelView.backgroundColor = UIColor.white
        } else {
            hud.contentColor = UIColor.white
            hud.bezelView.backgroundColor = UIColor.black
        }
    }
    
    func hideLoading() {
        DispatchQueue.main.async { [weak self] in
            if self == nil { return }
            let isExist = MBProgressHUD.hide(for: (self?.view)!, animated: false)
            if !isExist {
                let keyWindow = UIApplication.shared.delegate?.window
                MBProgressHUD.hide(for: keyWindow!!, animated: false)
            }
        }
    }
    
    // MARK: - 显示提示信息
    
    func showHUD(_ type: DZYHUDShowType, text: String, animated: Bool? = nil, afterDelay delay: TimeInterval? = nil, completionBlock: DZYHUDComplectionBlock? = nil) {
        var imageName = ""
        switch type {
        case .success: // 这里可以自定义 成功或者失败的图片消息
            imageName = "toast_success"
        case .failure:
            imageName = "toast_failure"
        case .alert:
            imageName = "toast_alert"
        }
        let toastImageView = UIImageView(image: UIImage(named: imageName))
        
        let newAnimated = animated ?? true
        let hud = MBProgressHUD.showAdded(to: view, animated: newAnimated)
        hud.margin = 15.0
        hud.mode = .customView
        hud.animationType = .fade
        hud.customView = toastImageView
        hud.removeFromSuperViewOnHide = true
        hud.bezelView.backgroundColor = UIColor.black
        
        // 文字提示信息
        if text != "" {
            hud.label.text = "  "
            hud.label.textColor = UIColor.black
            hud.label.font = UIFont.systemFont(ofSize: 2.0)
            
            hud.detailsLabel.text = text
            hud.detailsLabel.textColor = UIColor.white
            hud.detailsLabel.font = UIFont.systemFont(ofSize: 15.0)
        }
        
        // HUD 隐藏成功后的回调
        if completionBlock != nil {
            hud.completionBlock = completionBlock
        }
        // 自动隐藏 HUD
        let newDelay = delay ?? 1.75
        hud.hide(animated: false, afterDelay: newDelay)
    }

}
